// packageF/sachertorte/classify/classify.js
let app = getApp();
import util from "../../../utils/util";
let location = require("../../../mybehaviors/location/location");
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    search:'',
    tabActive:0,
    keyword:'',
    getBrand: [
    ],
    brandNum:11,
    goodsList: [],
    query: {
      page:1,
      city:'',
    },
    totalPage:0,
    isLoadMore: true,
    brandId:'', //区别是全部还是其他分类
    categorys:[ //分类信息
      {
        id: 0,
        name: "全部"
      }
    ],
    timer:'', //防抖时间
    categorysId:'', //分类ID
    brandsId:'', //品牌ID
    background_color:'#ffc11e',
    storageName: "sachertorte", // 蛋糕显示历史搜索记录
    showHistory:false,
  },
  hidebox(){
    this.setData({
      screenShow: false
    })
    let searchHistoryList = wx.getStorageSync(this.data.storageName);
    if (searchHistoryList.length > 0) {
      this.showHistory = true;
      this.setData({
        showHistory:true
      })
    }
  },
  searchBlur(){
    this.setData({
      showHistory:false
    })
  },
  searchChange(event) { //搜索事件
    this.setData({
      'query.page':1,
    })
    if(typeof(event.detail) != 'object') {
      this.setData({
        keyword:event.detail
      })
      this.selectComponent("#search_history").appendKeywords(this.data.keyword);
    }else{
      this.setData({
        keyword:''
      })
    }
    if (this.timer) clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      util.debounce(this.goodsByList());
    }, 500);
    
  },
  exhibitionOn() {  //展开
    this.setData({
      brandNum: this.data.getBrand.length
    })
  },
  packup() { //收起
    this.setData({
      brandNum: 11
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      // this.getBrandsData();
      if(options.id) {
        this.setData({
          tabActive: Number(options.id),
          categorysId: Number(options.id)
        })
        wx.setNavigationBarTitle({
          title: options.classifyName,
         })
      }
      if(this.data.tabActive === 0) {
        this.setData({
          brandId:0,
          brandsId:options.brandId || ''
        })
      }
      if(options.city) {
        this.setData({
          'query.city': options.city,
        })
      }
      this.categorysList(); 
     
  },
  brandClick(event) {
    let  id = event.currentTarget.dataset.id;
    this.setData({
      brandsId: id,
      'query.page':1,
    });
    this.goodsByList();
  },
  categorysChange(event) {
    this.setData({
      'query.page':1,
      categorysId: event.detail.name,
      tabActive: event.detail.index,
      brandId: event.detail.index
    })
    this.goodsByList();
  },
  categorysList() { //分类信息
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.index.index.getCategorys");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          let list = res.data;
          let categorys = this.data.categorys;
          for(let i in list) {
            categorys.push({
              id: list[i].id,
              name: list[i].name,
              thumb: list[i].thumb,
              thumb_url: list[i].thumb_url
            })
          }
          this.setData({
            categorys: categorys
          })
          
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getBrandsData() { //品牌列表
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.goods.goods.getBrand");
    let query = {
      city: this.data.query.city
    };
    app._getNetWork({
      url: urlStr,
      data:query,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          this.setData({
            getBrand: res.data
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  goodsByList() {
    wx.showLoading({
      title: '加载中',
    })
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.goods.goods.getGoodsList");
    urlStr += `&page=${this.data.query.page}`;
    urlStr += `&city=${this.data.query.city}`;
    urlStr += `&search[brand_id]=${this.data.brandsId}`;
    urlStr += `&search[category]=${this.data.categorysId}`;
    urlStr += `&search[keyword]=${this.data.keyword}`;
    app._getNetWork({
      url: urlStr,
      success:  (resdata) => {
        let res = resdata.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          this.data.totalPage = res.data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          this.setData({
            goodsList: res.data.data,
          })
        } else {
          this.data.page = this.data.page - 1;
          this.isLoadMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        wx.hideLoading();
        console.log(res);
      }
    });
  },
   //获取更多数据
   getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.query.page >= this.data.totalPage) {
      return;
    } else {
      wx.showLoading({
        title: '加载中',
      })
      this.data.query.page = this.data.query.page + 1;
      let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.goods.goods.getGoodsList");
      urlStr += `&page=${this.data.query.page}`;
      urlStr += `&city=${this.data.query.city}`;
      urlStr += `&search[brand_id]=${this.data.brandsId}`;
      urlStr += `&search[category]=${this.data.categorysId}`;
      urlStr += `&search[keyword]=${this.data.keyword}`;
      // let query = this.data.query;
      console.log(this.data.query);
      app._getNetWork({
        url: urlStr,
        data: this.data.query,
        success: (resdata) => {
          wx.hideLoading();
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              goodsList : this.data.goodsList.concat(list),
            })
          } else {
            this.data.query.page = this.data.query.page - 1;
            this.data.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          wx.hideLoading();
          console.log(res);
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        let city = mapdata.address_component.city;
        if(!this.data.query.city) {
          this.setData({
            'query.city':city
          });
        }
        //定位后调用首页接口和推荐列表接口
      this.getBrandsData();
      this.goodsByList();
      });
    } catch (e) {
      console.log(e);
      this.getBrandsData();
      this.goodsByList();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let basic_info = wx.getStorageSync('yz_basic_info');
    this.setData({
      background_color:basic_info.theme_color
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      isLoadMore: true,
      page: 1,
      totalPage: 0
    });
    this.getMoreData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})